package getstudent

import (
	"database/sql"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Sget(r *gin.Engine) {
	var db *sql.DB
	var err error
	var sid, name, gender, sdept, class, college string = "0", "0", "0", "0", "0", "0"

	db, err = sql.Open("postgres", "port=5432 user=postgres password=123456 dbname=postgres sslmode=disable")
	if err != nil {
		panic(err)
	}
// 获取全部学生信息
r.GET("/studentinfo", func(c *gin.Context) {

	str := "SELECT * FROM student"
	rows, err := db.Query(str)
	if err != nil {
		panic(err)
	}

	type stu struct {
		Sid      string `json:"sid"`
		Name     string `json:"name"`
		Gender   string `json:"gender"`
		Sdept     string `json:"sdept"`
		Class    string `json:"class"`
		College  string `json:"college"`
	}

	students := make([]*stu, 0)
	for rows.Next() {

		err = rows.Scan(&sid, &name, &gender, &sdept, &class, &college)
		if err != nil {
			panic(err)
		}

		students = append(students, &stu{
			Sid:      sid,
			Name:     name,
			Gender:   gender,
			Sdept:     sdept,
			Class:    class,
			College:	college,
		})
	}
	c.JSON(200, gin.H{
		"students": students,
	})
})

	// 获取搜索
	r.GET("/getstudent", func(c *gin.Context) {
		xx := c.Query("xx")
		if xx != "" {

			str := "SELECT * FROM student where sid='" + xx + "'"
			rows, err := db.Query(str)
			if err != nil {
				panic(err)
			}

			for rows.Next() {

				err = rows.Scan(&sid, &name, &gender, &sdept, &class, &college)
				if err != nil {
					panic(err)
				}

				c.JSON(200, gin.H{
					"sid":     sid,
					"name":    name,
					"gender":  gender,
					"sdept":   sdept,
					"class":   class,
					"college": college,
				})
			}
		}

	})

	// 添加用户
	r.GET("/insertstudent", func(c *gin.Context) {
		sid = c.Query("sid")
		name = c.Query("name")
		sdept = c.Query("sdept")
		class = c.Query("class1")
		college = c.Query("college")
		gender = c.Query("gender")
		if err != nil {
			panic(err)
		}
		str := "INSERT INTO student(sid,name,gender,college,sdept,class) VALUES($1,$2,$3,$4,$5,$6)"
		stmt, err := db.Prepare(str)
		if err != nil {
			panic(err)
		}

		res, err := stmt.Exec(sid, name, gender, college, sdept, class)
		if err != nil {
			panic(err)
		}

		affect, err := res.RowsAffected()
		if err != nil {
			panic(err)
		}

		fmt.Println("rows affect:", affect)
	})

}
